//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package imagetoolscommon;

import imagetoolscommon.ImageData;
import imagetoolscommon.ImageFileFilter;
import imagetoolscommon.ImageTileCutterThread;
import imagetoolscommon.TileObserver;
import imagetoolscommon.Utils;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import javax.swing.AbstractListModel;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import org.jdesktop.layout.GroupLayout;

public class BatchCreateDialog extends JDialog implements TileObserver {
    private ImageTileCutterThread cutterThread;
    private JFileChooser chooser = new JFileChooser();
    private Vector fileList = new Vector();
    private int processedFileCount = 0;
    private int skippedFileCount = 0;
    private PrintWriter logWriter;
    private String logFilename = null;
    private JButton addButton;
    private JButton cancelButton;
    private JLabel currentFileLabel;
    private JPanel jPanel1;
    private JProgressBar jProgressBar1;
    private JScrollPane jScrollPane1;
    private JLabel progressLabel;
    private JButton removeButton;
    private JButton startButton;
    private JList todoList;
    private JButton viewLogButton;

    public BatchCreateDialog(Frame parent, boolean modal) {
        super(parent, modal);
    }

    public BatchCreateDialog(Frame parent, boolean modal, ImageTileCutterThread cutterThread) {
        super(parent, modal);
        this.cutterThread = cutterThread;
        this.cutterThread.setTileObserver(this);
        this.initComponents();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = this.getSize();
        if(frameSize.height > screenSize.height) {
            frameSize.height = screenSize.height;
        }

        if(frameSize.width > screenSize.width) {
            frameSize.width = screenSize.width;
        }

        this.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
    }

    public void processingTile(String filename, int count, int totalCount) {
        this.progressLabel.setText("Tile: " + filename);
        if(totalCount > 0) {
            int percent = count * 100 / totalCount;
            this.jProgressBar1.setValue(percent);
            this.jProgressBar1.setString(Integer.toString(percent) + "%");
        }

    }

    public void finishedProcessingTiles(int totalCount) {
        ++this.processedFileCount;
        this.logWriter.println("Successfully created " + totalCount + " tiles.");
        this.logWriter.flush();
        this.jProgressBar1.setValue(100);
        this.progressLabel.setText("Successfully created " + totalCount + " tiles");
        this.doProcessing();
    }

    public void doProcessing() {
        ImageData imageData = null;

        while(this.fileList.size() > 0 && imageData == null) {
            File text = (File)this.fileList.get(0);
            this.logWriter.println("Processing " + text.getAbsolutePath());
            this.logWriter.flush();

            try {
                imageData = ImageData.loadFile(text);
            } catch (Exception var6) {
                ;
            }

            if(imageData == null) {
                ++this.skippedFileCount;
                this.logWriter.println("Error: file " + text.getAbsolutePath() + " could not be loaded - skipping image");
                this.logWriter.flush();
            }

            this.fileList.remove(0);
            this.todoList.setListData(this.fileList);
        }

        String text1;
        if(imageData == null) {
            text1 = "";
            if(this.processedFileCount == 1) {
                text1 = "1 file processed successfully, ";
            } else {
                text1 = this.processedFileCount + " files processed successfully, ";
            }

            if(this.skippedFileCount == 0) {
                text1 = text1 + "no errors.";
            } else if(this.skippedFileCount == 1) {
                text1 = text1 + "1 file failed due to errors.";
            } else {
                text1 = text1 + this.skippedFileCount + " files failed due to errors.";
            }

            this.logWriter.println(text1);
            this.logWriter.close();
            this.currentFileLabel.setText(text1);
            this.progressLabel.setText("Batch convert complete.");
            this.cancelButton.setText("Finish");
            this.viewLogButton.setEnabled(true);
        } else {
            text1 = "Processing: " + imageData.filename;
            if(this.fileList.size() > 0) {
                text1 = text1 + " (" + this.fileList.size() + " remaining)";
            }

            this.currentFileLabel.setText(text1);
            ImageTileCutterThread thread = null;

            try {
                thread = (ImageTileCutterThread)this.cutterThread.clone();
                int ex = ImageTileCutterThread.calculateMaxZoomDepth(imageData.image.getWidth(), imageData.image.getHeight());
                thread.setImageData(imageData);
                thread.start();
            } catch (Exception var5) {
                ++this.skippedFileCount;
                thread.abortCreate();
                this.progressLabel.setText("Create aborted.");
                this.logWriter.println("Error processing " + imageData.filename + " - aborted");
                var5.printStackTrace(this.logWriter);
            }

        }
    }

    private void initComponents() {
        this.jScrollPane1 = new JScrollPane();
        this.todoList = new JList();
        this.addButton = new JButton();
        this.removeButton = new JButton();
        this.cancelButton = new JButton();
        this.startButton = new JButton();
        this.jPanel1 = new JPanel();
        this.progressLabel = new JLabel();
        this.jProgressBar1 = new JProgressBar();
        this.currentFileLabel = new JLabel();
        this.viewLogButton = new JButton();
        this.setDefaultCloseOperation(2);
        this.setTitle("Batch Process Files");
        this.todoList.setModel(new AbstractListModel() {
            String[] strings = new String[]{"Add files to be processed.", "Use <SHIFT> or <CTRL> keys to select multiple files."};

            public int getSize() {
                return this.strings.length;
            }

            public Object getElementAt(int i) {
                return this.strings[i];
            }
        });
        this.jScrollPane1.setViewportView(this.todoList);
        this.addButton.setText("Add Files...");
        this.addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                BatchCreateDialog.this.addButtonActionPerformed(evt);
            }
        });
        this.removeButton.setText("Remove");
        this.removeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                BatchCreateDialog.this.removeButtonActionPerformed(evt);
            }
        });
        this.cancelButton.setText("Cancel");
        this.cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                BatchCreateDialog.this.cancelButtonActionPerformed(evt);
            }
        });
        this.startButton.setText("Start");
        this.startButton.setEnabled(false);
        this.startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                BatchCreateDialog.this.startButtonActionPerformed(evt);
            }
        });
        this.jPanel1.setBorder(BorderFactory.createTitledBorder("Progress"));
        this.progressLabel.setText("Waiting...");
        this.jProgressBar1.setStringPainted(true);
        GroupLayout jPanel1Layout = new GroupLayout(this.jPanel1);
        this.jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(1).add(jPanel1Layout.createSequentialGroup().addContainerGap().add(jPanel1Layout.createParallelGroup(1).add(this.jProgressBar1, -1, 348, 32767).add(this.progressLabel).add(this.currentFileLabel)).addContainerGap()));
        jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(1).add(2, jPanel1Layout.createSequentialGroup().add(this.currentFileLabel).addPreferredGap(0, -1, 32767).add(this.progressLabel).addPreferredGap(0).add(this.jProgressBar1, -2, -1, -2).addContainerGap()));
        this.viewLogButton.setText("View Log...");
        this.viewLogButton.setEnabled(false);
        this.viewLogButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                BatchCreateDialog.this.viewLogButtonActionPerformed(evt);
            }
        });
        GroupLayout layout = new GroupLayout(this.getContentPane());
        this.getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(1).add(2, layout.createSequentialGroup().addContainerGap().add(layout.createParallelGroup(2).add(1, this.jPanel1, -1, -1, 32767).add(layout.createSequentialGroup().add(this.viewLogButton).addPreferredGap(0).add(this.startButton).addPreferredGap(0).add(this.cancelButton).addPreferredGap(0)).add(layout.createSequentialGroup().add(this.jScrollPane1, -1, 287, 32767).addPreferredGap(0).add(layout.createParallelGroup(1, false).add(this.removeButton, -1, -1, 32767).add(this.addButton, -1, -1, 32767)))).addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(1).add(layout.createSequentialGroup().addContainerGap().add(layout.createParallelGroup(2).add(1, layout.createSequentialGroup().add(this.addButton).addPreferredGap(0).add(this.removeButton)).add(1, this.jScrollPane1, -2, 164, -2)).addPreferredGap(0).add(this.jPanel1, -2, -1, -2).add(20, 20, 20).add(layout.createParallelGroup(3).add(this.startButton).add(this.cancelButton).add(this.viewLogButton)).add(22, 22, 22)));
        this.pack();
    }

    private void viewLogButtonActionPerformed(ActionEvent evt) {
        JTextArea textArea = new JTextArea(10, 80);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);
        textArea.setText("");

        try {
            BufferedReader ex = new BufferedReader(new FileReader(this.logFilename));

            String sw1;
            try {
                while((sw1 = ex.readLine()) != null) {
                    textArea.append(sw1 + "\n");
                }
            } finally {
                ex.close();
            }
        } catch (Exception var10) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            var10.printStackTrace(pw);
            textArea.append("Exception:\n" + sw.getBuffer().toString());
        }

        textArea.setCaretPosition(0);
        JOptionPane.showMessageDialog(this, scrollPane, this.logFilename, 1);
    }

    private void removeButtonActionPerformed(ActionEvent evt) {
        int idx = this.todoList.getSelectedIndex();
        if(idx >= 0) {
            this.fileList.remove(idx);
            this.todoList.setListData(this.fileList);
        }

        if(this.fileList.size() <= 0) {
            this.startButton.setEnabled(false);
        }

    }

    private void addButtonActionPerformed(ActionEvent evt) {
        this.chooser.setAcceptAllFileFilterUsed(true);
        this.chooser.setFileFilter(new ImageFileFilter());
        this.chooser.setMultiSelectionEnabled(true);
        if(this.chooser.showOpenDialog(this) == 0) {
            File[] files = this.chooser.getSelectedFiles();

            for(int i = 0; i < files.length; ++i) {
                this.fileList.add(files[i]);
            }

            this.todoList.setListData(this.fileList);
            this.startButton.setEnabled(true);
        }

    }

    private void cancelButtonActionPerformed(ActionEvent evt) {
        this.cutterThread.abortCreate();
        if(this.logWriter != null) {
            this.logWriter.write("Batch convert terminated at user request.");
            this.logWriter.close();
        }

        this.progressLabel.setText("Create aborted.");
        this.setVisible(false);
        this.dispose();
    }

    private void startButtonActionPerformed(ActionEvent evt) {
        this.startButton.setEnabled(false);
        this.cancelButton.setEnabled(true);
        this.addButton.setEnabled(false);
        this.removeButton.setEnabled(false);

        try {
            File ex = (File)this.fileList.get(0);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
            this.logFilename = ex.getParent() + File.separator + "batchprocess_" + formatter.format(new Date()) + ".log";
            this.logWriter = new PrintWriter(new FileWriter(this.logFilename));
            this.doProcessing();
        } catch (Exception var4) {
            Utils.showErrorDialogBox(this, "Error in batch export", "Error in batch export initialisation", var4);
        }

    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                (new BatchCreateDialog(new JFrame(), true)).setVisible(true);
            }
        });
    }
}
